package cn.com.wxd.action.admin.website;

import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.wxd.action.AjaxResult;
import cn.com.wxd.action.ValidatorResult;
import cn.com.wxd.biz.website.ArticleService;
import cn.com.wxd.biz.website.CatalogService;
import cn.com.wxd.biz.website.WebsiteCache;
import cn.com.wxd.entity.user.AccountInfo;
import cn.com.wxd.entity.website.ArticleInfo;
import cn.com.wxd.entity.website.CatalogInfo;
import cn.com.wxd.common.DateUtil;
import cn.com.wxd.common.PageInfo;
import cn.com.wxd.common.data.KeyValue;
import cn.com.wxd.util.user.UserCoreUtil;
import cn.com.wxd.util.website.CatalogTree;
import cn.com.wxd.util.website.CatalogTreeEntity;
import cn.com.wxd.util.website.WebsiteInfo;

/**
 * Title:
 * Description:
 * <p>
 * Company: Amumu管理平台
 * Copyright: Copyright (c) 2017
 * All right reserved.
 * Created by WangXuDong on 2017/6/9.
 *
 * @author WangXuDong
 * @version 1.0
 */
@Controller
@RequestMapping("/admin/website/article")
public class ArticleCtl {

    private static final Logger log = LoggerFactory.getLogger(ArticleCtl.class);
    @Resource
    private ArticleService articleService; //服务层

    @Resource
    private CatalogService catalogService;//服务层

    /**
     * 栏目树页面
     *
     * @param caid
     * @param map
     *
     * @return
     */
    @RequestMapping("/catalogTree")
    public String catalogTree(@RequestParam(required = false) String caid, ModelMap map) {
        String catalogTreeDom;
        List<CatalogInfo> allCatalogs = catalogService.getAllCatalog(new HashMap<String, String>());
        map.put("allCatalogs", allCatalogs);
        map.put("caid", caid);
        if (WebsiteInfo.isCache()) {
            // 先从缓存中获取
            Object catalogTreeDomo = WebsiteCache.getWebsiteObjectCache("catalogTreeDom");
            if (catalogTreeDomo != null && !catalogTreeDomo.equals("")) {
                catalogTreeDom = String.valueOf(catalogTreeDomo);
                map.put("catalogTreeDom", catalogTreeDom);
                return "/admin/website/article/catalog";
            }
        }
        CatalogTree ct = new CatalogTree(allCatalogs);
        catalogTreeDom = ct.getCatalogTreeHTML(new CatalogTreeEntity());
        if (WebsiteInfo.isCache()) {
            // 放入缓存
            WebsiteCache.setWebsiteObjectCache("catalogTreeDom", catalogTreeDom);
        }
        map.put("catalogTreeDom", catalogTreeDom);
        return "/admin/website/article/catalog";
    }

    /**
     * 获取文章列表根据栏目号
     *
     * @param caid
     * @param page
     * @param map
     *
     * @return
     */
    @RequestMapping("/articlelist")
    public String articleListByCataId(String caid, PageInfo page, ModelMap map) {
        List<KeyValue<Integer, String>> list = catalogService.getCatalogNav(caid);
        // 设置导航栏字符串
        String cataNav = "";
        for (int i = list.size() - 1; i >= 0; i--) {
            if (cataNav.equals("")) {
                cataNav = list.get(i).getValue();
                continue;
            }
            cataNav += " > " + list.get(i).getValue();
        }
        List<ArticleInfo> aritcleList = articleService.getArticles(caid, page);
        map.put("cataNav", cataNav);
        map.put("aritcleList", aritcleList);
        map.put("caid", caid);
        map.put("page", page);
        return "/admin/website/article/articlelist";
    }

    /**
     * 添加文章
     *
     * @return
     */
    @RequestMapping("/addArticle")
    public String addArticle(String caid, HttpServletRequest request, ModelMap map) {
        AccountInfo accountInfo = UserCoreUtil.getLoginAccount(request);
        ArticleInfo articleInfo = new ArticleInfo();
        if (accountInfo != null) {
            articleInfo.setDateTime(DateUtil.getDatetimeStr());
            articleInfo.setAuthor(accountInfo.getUsersInfo().getNickName());
        }
        map.put("articleInfo", articleInfo);
        map.put("caid", caid);
        return "/admin/website/article/addarticle";
    }

    /**
     * 文章更新
     *
     * @return
     */
    @RequestMapping("/updateArticle")
    public String updateArticle(HttpServletRequest request, String id, ModelMap map) {
        map.put("actionType", "update");
        AccountInfo accountInfo = UserCoreUtil.getLoginAccount(request);
        ArticleInfo articleInfo = articleService.getArticle(id, false);
        if (articleInfo != null) {
            articleInfo.setDateTime(DateUtil.getDatetimeStr());
            articleInfo.setAuthor(accountInfo.getUsersInfo().getNickName());
        } else {
            return "redirect:/admin/website/article/addArticle";
        }
        String caid = String.valueOf(articleInfo.getCaId());
        map.put("articleInfo", articleInfo);
        map.put("caid", caid);
        return "/admin/website/article/addarticle";
    }

    /**
     * 保存文章
     *
     * @param articleInfo
     * @param map
     * @param attributes
     *
     * @return
     */
    @RequestMapping(value = "/saveArticle", method = RequestMethod.POST)
    public String saveArticle(ArticleInfo articleInfo, ModelMap map, RedirectAttributes attributes) {
        ValidatorResult validatorResult = ArticleCtlValidator.validatorSaveArticle(articleInfo);
        if (validatorResult.isFailure()) {
            //如果出错了
            map.put("articleInfo", articleInfo);
            map.put("caid", articleInfo.getCaId());
            map.put("actionError", validatorResult.getMessage());
            return "/admin/website/article/addarticle";
        }
        boolean result = articleService.saveArticle(articleInfo);
        if (!result) {
            map.put("articleInfo", articleInfo);
            map.put("caid", articleInfo.getCaId());
            map.put("actionError", "未知原因!添加文章失败!");
            return "/admin/website/article/addarticle";
        }
        attributes.addAttribute("caid", articleInfo.getCaId());
        return "redirect:/admin/website/article/catalogTree";
    }

    /**
     * 根据ID查找文章
     *
     * @return
     */
    @RequestMapping(value = "/fetchArticle/{id}")
    @ResponseBody
    public AjaxResult fetchArticleById(@PathVariable String id) {
        return AjaxResult.successResult(articleService.getArticle(id, false));
    }

    /**
     * 复制文章
     *
     * @return
     */
    @RequestMapping(value = "/cloneArticle")
    @ResponseBody
    public AjaxResult cloneArticle(@RequestParam String ids, @RequestParam String caid) {

        if (articleService.cloneArticle(ids, caid)) {
            return AjaxResult.successResult();
        }
        return AjaxResult.failureResult("cloneArticle Failure");
    }

    /**
     * 移动文章
     *
     * @return
     */
    @RequestMapping(value = "/moveArticle")
    @ResponseBody
    public AjaxResult moveArticle(@RequestParam String ids, @RequestParam String caid) {
        if (articleService.moveArticle(ids, caid)) {
            return AjaxResult.successResult();
        }
        return AjaxResult.failureResult("moveArticle Failure");
    }

    /**
     * 删除文章
     *
     * @return
     */
    @RequestMapping(value = "/batchDeleteArticle")
    @ResponseBody
    public AjaxResult batchDeleteArticle(@RequestParam String ids) {
        if (articleService.batchDeleteA(ids)) {
            return AjaxResult.successResult();
        }
        return AjaxResult.failureResult("batchDeleteArticle Failure");
    }

    /**
     * 重建文章索引
     *
     * @return
     */
    @RequestMapping(value = "/reBuildArticleIndex")
    @ResponseBody
    public AjaxResult reBuildArticleIndex() {
        if (articleService.reBuildIndex()) {
            return AjaxResult.successResult();
        }
        return AjaxResult.failureResult("reBuildArticleIndex Failure");
    }

    /**
     * 文章的排序
     *
     * @return
     */
    @RequestMapping(value = "/articleSorting")
    @ResponseBody
    public AjaxResult articleSorting(@RequestParam String newOrdId, @RequestParam String oldOrdId) {
        if (articleService.rankArticle(newOrdId, oldOrdId)) {
            return AjaxResult.successResult();
        }
        return AjaxResult.failureResult("articleSorting Failure");
    }

    /**
     * 搜索文章
     *
     * @return
     */
    @RequestMapping(value = "/searchArticle")
    public String searchArticle(String searchType, String searchKeyWord,
                                PageInfo page, ModelMap map, HttpSession session) {
        String cataNav = "搜索结果:";
        KeyValue<String, String> kv = new KeyValue<>();  //设置关键字参数
        kv.setKey(searchType);
        kv.setValue(searchKeyWord);
        String searchT;  //查询类型
        if (searchType.equals("content")) {
            searchT = "IN";
        } else {
            searchT = "DB";
        }
        List<ArticleInfo> aritcleList = articleService.searchArticle(searchT, kv, page);
        searchType = kv.getKey();  //返回到前端页面
        searchKeyWord = kv.getValue();
        session.setAttribute("admin_searchKeyWord", searchKeyWord);
        session.setAttribute("admin_searchType", searchType);
        map.put("cataNav", cataNav);
        map.put("aritcleList", aritcleList);
        map.put("page", page);
        return "/admin/website/article/articlelist";
    }

    /**
     * 初始化了articleInfo的参数绑定前缀
     *
     * @param binder
     */
    @InitBinder("articleInfo")
    public void initBinderArticleInfo(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("articleInfo.");
    }
}
